<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
      <title>Dependency Injection Guidelines | HiAPI-C# 2025 </title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="title" content="Dependency Injection Guidelines | HiAPI-C# 2025 ">
      
      
      <link rel="icon" href="../../../../img/HiAPI.favicon.ico">
      <link rel="stylesheet" href="../../../../public/docfx.min.css">
      <link rel="stylesheet" href="../../../../public/main.css">
      <meta name="docfx:navrel" content="../../../../toc.html">
      <meta name="docfx:tocrel" content="../../toc.html">
      
      <meta name="docfx:rel" content="../../../../">
      
      
      
      <meta name="loc:inThisArticle" content="In this article">
      <meta name="loc:searchResultsCount" content="{count} results for &quot;{query}&quot;">
      <meta name="loc:searchNoResults" content="No results for &quot;{query}&quot;">
      <meta name="loc:tocFilter" content="Filter by title">
      <meta name="loc:nextArticle" content="Next">
      <meta name="loc:prevArticle" content="Previous">
      <meta name="loc:themeLight" content="Light">
      <meta name="loc:themeDark" content="Dark">
      <meta name="loc:themeAuto" content="Auto">
      <meta name="loc:changeTheme" content="Change theme">
      <meta name="loc:copy" content="Copy">
      <meta name="loc:downloadPdf" content="Download PDF">

      <script type="module" src="./../../../../public/docfx.min.js"></script>

      <script>
        const theme = localStorage.getItem('theme') || 'auto'
        document.documentElement.setAttribute('data-bs-theme', theme === 'auto' ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme)
      </script>

  </head>

  <body class="tex2jax_ignore" data-layout="" data-yaml-mime="">
    <header class="bg-body border-bottom">
      <nav id="autocollapse" class="navbar navbar-expand-md" role="navigation">
        <div class="container-xxl flex-nowrap">
          <a class="navbar-brand" href="../../../../index.html">
            <img id="logo" class="svg" src="../../../../img/HiAPI.logo.png" alt="">
            
          </a>
          <button class="btn btn-lg d-md-none border-0" type="button" data-bs-toggle="collapse" data-bs-target="#navpanel" aria-controls="navpanel" aria-expanded="false" aria-label="Toggle navigation">
            <i class="bi bi-three-dots"></i>
          </button>
          <div class="collapse navbar-collapse" id="navpanel">
            <div id="navbar">
              <form class="search" role="search" id="search">
                <i class="bi bi-search"></i>
                <input class="form-control" id="search-query" type="search" disabled placeholder="Search" autocomplete="off" aria-label="Search">
              </form>
            </div>
          </div>
        </div>
      </nav>
    </header>

    <main class="container-xxl">
      <div class="toc-offcanvas">
        <div class="offcanvas-md offcanvas-start" tabindex="-1" id="tocOffcanvas" aria-labelledby="tocOffcanvasLabel">
          <div class="offcanvas-header">
            <h5 class="offcanvas-title" id="tocOffcanvasLabel">Table of Contents</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" data-bs-target="#tocOffcanvas" aria-label="Close"></button>
          </div>
          <div class="offcanvas-body">
            <nav class="toc" id="toc"></nav>
          </div>
        </div>
      </div>

      <div class="content">
        <div class="actionbar">
          <button class="btn btn-lg border-0 d-md-none" type="button" data-bs-toggle="offcanvas" data-bs-target="#tocOffcanvas" aria-controls="tocOffcanvas" aria-expanded="false" aria-label="Show table of contents">
            <i class="bi bi-list"></i>
          </button>

          <nav id="breadcrumb"></nav>
        </div>

        <article data-uid="">
          <h1 id="dependency-injection-guidelines">Dependency Injection Guidelines</h1>

<p>This document describes how to apply Dependency Injection (DI) across HiAPI apps, and how to migrate from legacy <code>LocalApp</code> usage.</p>
<h2 id="why-di">Why DI</h2>
<ul>
<li>Centralize service registration and lifetime management</li>
<li>Improve testability and replaceability</li>
<li>Remove hidden global state and implicit dependencies</li>
</ul>
<h2 id="web-api-entry-example">Web API Entry Example</h2>
<p>Register services in <code>Program.cs</code> using <code>WebApplicationBuilder</code>.</p>
<pre><code class="lang-csharp">var builder = WebApplication.CreateBuilder(args);

// Framework services
builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddEndpointsApiExplorer();

// Cross-cutting
builder.Services.AddSignalR(o =&gt; o.MaximumReceiveMessageSize = 10 * 1024 * 1024);
builder.Services.AddCors(o =&gt; o.AddPolicy(&quot;AllowAll&quot;, p =&gt; p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

// Application services
builder.Services.AddSingleton&lt;Hi.Webapi.Services.RenderingService&gt;();

// Optional
builder.Services.Configure&lt;Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions&gt;(o =&gt; o.AllowSynchronousIO = true);

var app = builder.Build();

// Lifecycle hooks
var lifetime = app.Services.GetRequiredService&lt;IHostApplicationLifetime&gt;();
lifetime.ApplicationStopping.Register(() =&gt; {
    // graceful cleanup
});

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseCors(&quot;AllowAll&quot;);
app.UseAuthorization();
app.MapControllers();
app.MapHub&lt;Hi.Webapi.Hubs.RenderingHub&gt;(&quot;/renderingHub&quot;);
app.Run();
</code></pre>
<h2 id="grpc-hosting-via-di">gRPC Hosting via DI</h2>
<pre><code class="lang-csharp">var builder = WebApplication.CreateBuilder();
builder.Services.AddGrpc();
builder.Services.AddScoped(_ =&gt; clStripServiceRunner);
builder.Services.AddScoped(_ =&gt; playerServiceRunner);

builder.WebHost.ConfigureKestrel(o =&gt;
{
    o.ListenLocalhost(servicePort, o =&gt; o.Protocols = HttpProtocols.Http2);
});

var app = builder.Build();
app.MapGrpcService&lt;ClStripServiceRunner&gt;();
app.MapGrpcService&lt;PlayerServiceRunner&gt;();
await app.StartAsync();
</code></pre>
<h2 id="injecting-user-environment-and-config">Injecting User Environment and Config</h2>
<p>Prefer injecting <code>UserEnv</code> and <code>UserConfig</code> (or repositories/stores that handle them) into UI and controllers.</p>
<pre><code class="lang-csharp">public interface IUserConfigStore { Task SaveAsync(UserConfig config); }
public sealed class UserConfigStore : IUserConfigStore
{
    public Task SaveAsync(UserConfig config)
    {
        // persist config
        return Task.CompletedTask;
    }
}

builder.Services.AddSingleton&lt;IUserConfigStore, UserConfigStore&gt;();
</code></pre>
<h2 id="migration-from-localapp-legacy">Migration from LocalApp (Legacy)</h2>
<p>Legacy APIs:</p>
<ul>
<li>&lt;xref:Hi.HiNcKits.LocalApp.AppBegin()&gt;</li>
<li>&lt;xref:Hi.HiNcKits.LocalApp.AppEnd()&gt;</li>
</ul>
<p>Migration tips:</p>
<ul>
<li>Move initialization logic into DI registrations and hosted services</li>
<li>Replace direct accesses to <code>LocalApp</code> globals by injected services</li>
<li>Use <code>IHostApplicationLifetime</code> for shutdown hooks</li>
</ul>
<blockquote>
<p>For compatibility, legacy calls can remain while gradually moving responsibilities into DI.</p>
</blockquote>

</article>

        <div class="contribution d-print-none">
        </div>

        <div class="next-article d-print-none border-top" id="nextArticle"></div>

      </div>

      <div class="affix">
        <nav id="affix"></nav>
      </div>
    </main>

    <div class="container-xxl search-results" id="search-results"></div>

    <footer class="border-top text-secondary">
      <div class="container-xxl">
        <div class="flex-fill">
          <span> Copyright © 2025 <a href='https://superhightech.com.tw'>Tech Coordinate</a>. All rights reserved. <a href='https://superhightech.com.tw'>超級高科技股份有限公司</a> © 2025 版權所有 </span>
        </div>
      </div>
    </footer>
  </body>
</html>
